﻿using System;
using EasyStep.Attributes;
using EasyStep.TestExecution.Data;
using EasyStep.TestExecution.Interfaces;
using OpenQA.Selenium;
using EasyStep.TestActions.Utils;
using System.Diagnostics;
using System.Threading;

namespace EasyStep.TestActions.Actions.Wait
{
    [TestAction(typeof(Wait), Name = "WaitForTextPresent", RequireLocator = false)]
    class WaitForTextPresent : ITestAction<IWebDriver>
    {
        const int waitRetryDelayMs = 100; 
        const int timeOut = 500;  
        bool first = true; 

        public void Execute(IWebDriver browser, TestStepResult data, IExecuteDataContext context)
        {
            for (int milliSecond = 0; ; milliSecond += waitRetryDelayMs)
            {
                if (milliSecond > timeOut * 1000)
                {
                    break; // элемент не найден
                }

                if (browser.PageSource.Contains(data.Data))
                {
                    if (!first)
                    break; // элемент найден
                }
                
                else
                //if (first)  // еще ждем
                first = false;
                Thread.Sleep(waitRetryDelayMs);
            }
        }
    }
}
